function [ChEstimate_OUT,error] = HF_LSChEstimateSubtacting(ChOutput,ChInput,ChLength)
% ***************************************************
% 
% INPUTS:
%        ChOutput : The outputs of the channel sampled at one sample per symbol
%        ChInput  : The input symbols to the channel sampled at one sample per symbol 
%        ChLength : Length of composite channel
%
% OUTPUTS:
%       ChEstimate: estimated composite channel, i.e. (KnownCh*UnKnownCh)
%       error2    : square sum of the estimation error.
% ********************************************************
ChEstimate_OUT = zeros(1,ChLength);
Oversample = 4;

ChOutput_test = ChOutput(6*Oversample+1:end);
ChInput_test = ChInput(6*Oversample+1:end);
% Filter_Length = 12;   % in units of symbols
% Rolloff = 0.385;      % rolloff factor that satisfies the standard requirements on the filter (by trail)
% % Generate the Raised cosine filter
% %-------------------------------------
% HF_SRRC = rcosfir(Rolloff,Filter_Length/2,Oversample,1,'sqrt');
% HF_RRC = conv(HF_SRRC,HF_SRRC);

ChLength_DownSampled = ceil(ChLength/Oversample);
N_Path = ChLength_DownSampled;  % number of output valued paths

for path_no = 1:5 %N_Path

    for phase = 1:Oversample
        Ch_IN(phase,:) = ChInput_test(1:Oversample:end);
        Ch_OUT(phase,:) = ChOutput_test(phase:Oversample:end);
        
        %%----------------------------------------------------
        for index = 1:ChLength_DownSampled    % span of paths
            H(:,index) = Ch_IN(phase,ChLength_DownSampled-index+1:end-index+1).';
        end
        
        ChEstimate(phase,:) = pinv(H'*H)*H'*Ch_OUT(phase,ChLength_DownSampled:end).';
        %%----------------------------------------------------
    end
    
    Path_values = (reshape(ChEstimate,1,[]));
    [Path_abs path_index] = max(abs(Path_values));
    Path(path_no) = Path_values(path_index);
    if ChEstimate_OUT(path_index) == 0
        ChEstimate_OUT(path_index) = Path(path_no);
    end
    
    Path_Effect = Path(path_no)*ChInput;
    ChOutput = ChOutput - [zeros(1,path_index-1) Path_Effect(1:end-path_index+1)];
    
    ChOutput_test = ChOutput(6*Oversample+1:end);
    
end

ChOutput_fromestimation = conv(ChInput,ChEstimate_OUT);

ChOutput_fromestimation = ChOutput_fromestimation(1:length(ChOutput));

error_vector = ChOutput_fromestimation - ChOutput;

error = mean (abs(error_vector).^2);

